var action;

function mostrarJSON(data){
/*Mostrar el JSON que nos devuelve campus-cloud-server-rb*/
        
        //Borramos el contenedor central para mostrar los datos.
        $('#container').empty();
        
        //Variable en la almacenaremos el codigo html que se insertara al en el contenedor central
        var html='';
        	
        //Comprobamos si la BD nos ha devuelto una consulta vacia
        if(!$.isEmptyObject(data)){
		html+= '<table id="table_id">';
			switch (action){
				case 'profile':
				//falta darle funcionalidadddddddddddddd	
				break;
			
				case 'list':
					html+='<thead>';
						html+='<tr>';
							html+='<th>NAME</th>';
							html+='<th>GROUP</th>';
							html+='<th>LAB DESCRIPTION</th>';
							html+='<th>TEMPLATE DESCRIPTION</th>';
							html+='<th>TEACHER</th>';
						html+='</tr>';
					html+='</thead>';
					html+='<tbody>';
                
					//Recorremos el JSON objeto por objeto
					$.each(data, function(key, val) {
						html+='<tr>';
						html+= '<td>'+ val.lab_name +'</td>';
						html+= '<td>'+ val.lab_group +'</td>';
						html+= '<td>'+ val.lab_description +'</td>';
						html+= '<td>'+ val.template_description +'</td>';
						html+= '<td>'+ val.surname+', '+val.name +'</td>';
						html+='</tr>';
					});
					html+='</tbody>';
                			html+= '</table>';
				break;
				
				case 'create':
					html+='<thead>';
						html+='<tr>';
							html+='<th></th>';
							html+='<th>NAME</th>';
							html+='<th>TEMPLATE DESCRIPTION</th>';
							
						html+='</tr>';
					html+='</thead>';
					html+='<tbody>';
                
					//Recorremos el JSON objeto por objeto
					$.each(data, function(key, val) {
						html+='<tr>';
						html+= '<td><input type="checkbox" name="chk" value="'+val.id+'"/></td>';
						html+= '<td>'+ val.template_name +'</td>';
						html+= '<td>'+ val.template_description +'</td>';
						html+='</tr>';
					});
					html+='</tbody>';
                			html+= '</table>';
					html+='<br><input type="button" id="createButton" class="button" value="Create Lab" onClick="createLab()"/>';
				break;
				
				case 'delete':
					html+='<thead>';
						html+='<tr>';
							html+='<th></th>';
							html+='<th>NAME</th>';
							html+='<th>GROUP</th>';
							html+='<th>LAB DESCRIPTION</th>';
							html+='<th>TEMPLATE DESCRIPTION</th>';
							html+='<th>TEACHER</th>';
						html+='</tr>';
					html+='</thead>';
					html+='<tbody>';
                
					//Recorremos el JSON objeto por objeto
					$.each(data, function(key, val) {
						html+='<tr>';
						html+= '<td><input type="checkbox" name="chk" value="'+val.lab_id+'"/></td>';
						html+= '<td>'+ val.lab_name +'</td>';
						html+= '<td>'+ val.lab_group +'</td>';
						html+= '<td>'+ val.lab_description +'</td>';
						html+= '<td>'+ val.template_description +'</td>';
						html+= '<td>'+ val.surname+', '+val.name +'</td>';
						html+='</tr>';
					});
					html+='</tbody>';
                			html+= '</table>';
					html+='<br><input type="button" id="deleteButton" class="button" value="Delete Lab" onClick="deleteLab()"/>';
				break;
			}
 
	}

        //Si nuestra consulta nos ha devuelto un JSON vacio (es decir, nil) mostramos un aviso
        else{
		if (action=="delete") html+='You havent got any lab'
                else html+= 'The are no data to show';
        }
                        
        //Insertamos en el contenedor central el codigo html definitivo que hemos generado tras analizar el JSON devuelto en la consulta
        $('#container').append(html);
	$('#table_id').dataTable({
		"bPaginate": false,
		"bInfo": false,
		"bSort": true,
		"bSortClasses": false	
	});
}

function createLab(){

	if ($(":checkbox").filter(":checked").length>1){
		alert("Only one template can be checked !");
	}
	else if ($(":checkbox").filter(":checked").length<1){
		alert("Please, check one template");
	}
	else{
		var templateID = $(":checkbox").filter(":checked").val();
		var html2 = '<div id="createLab">'
				
		html2+='<form id="createLabForm">';
		html2+='<br>';
                html2+='<table>';
		html2+='<tbody>';
		html2+='<tr>';
		html2+='<td align="right"><b>Lab name:</b></td>';
		html2+='<td align="left"><input type="text" size="15" name="labName" id="labName"/><br></td>';
		html2+='</tr>';
		html2+='<tr>';
		html2+='<td align="right"><b>Group:</b></td>';
		html2+='<td align="left"><input type="text" size="1" name="labGroup" id="labGroup"/><br></td>';
		html2+='</tr>';
		html2+='<tr>';
		html2+='<td align="right" valign="top"><b>Description: </b></td>';
		html2+='<td align="left"><textarea name="labDescription" id="labDescription" rows="3" cols="20"></textarea></td>';
		html2+='</tr>';
      		html2+='<tr>';
                html2+='<td colspan="2" align="center"><input type="button" class="button" id="labButton" value="Create!"/></td>';
		html2+='</tr>';
		html2+='</tbody>';
		html2+='</table>';
        	html2+='</form>';

		html2+='</div>';
		
		$('#container').append(html2);
		$('#labButton').click(function () {
        		create(templateID);
    		});
	}
}
function create(templateID){
	if ($("#labName").val().length<2)
		alert("Lab name length must be 2 letters at least");
	else if ($("#labGroup").val().length!=1)
		alert("Lab group must be 1 letter");
	else if ($("#labDescription").val().length<1)
		alert("Lab description is empty. Please, enter a description for this lab");
	else{
		var labN = $("#labName").val();
		var labG= $("#labGroup").val();
		var labD = $("#labDescription").val();

		$.ajax({
                url: "/teachers/create",
		type:"POST",
		data:{template: templateID,labName: labN, labGroup: labG, labDescription: labD},
                success: function(){
			var html3='<div id="createDialog" title="Congratulations"> The lab has been created successfully</div>';
			$('#container').append(html3);
			$('#createDialog').dialog({
   				close: function() { 
					pedirJSON("list");
					action = "list"; 
					}
				});	
		},
                error: function(){
			var html3='<div id="createDialog" title="Sorry"> An error ocurred when the server tried to create the Lab</div>';
			$('#container').append(html3);
			$('#createDialog').dialog({
   				close: function() { 
					pedirJSON("create");
					action = "create"; 
					}
				});	
		}
            	});
	}				
}

function deleteLab(){

	if ($(":checkbox").filter(":checked").length>1){
		alert("Only one lab can be checked for delete!");
	}
	else if ($(":checkbox").filter(":checked").length<1){
		alert("Please, check one lab for delete");
	}
	else{
		var lab_ID = $(":checkbox").filter(":checked").val();		

		$.ajax({
                url: "/teachers/delete",
		type:"POST",
		data:{labID: lab_ID},
                success: function(){
			var html3='<div id="deleteDialog" title="Congratulations"> The lab has been deleted successfully</div>';
			$('#container').append(html3);
			$('#deleteDialog').dialog({
   				close: function() { 
					pedirJSON("list");
					action = "list"; 
					}
				});	
		},
                error: function(){
			var html3='<div id="deleteDialog" title="Sorry"> An error ocurred when the server tried to delete the Lab</div>';
			$('#container').append(html3);
			$('#deleteDialog').dialog({
   				close: function() { 
					pedirJSON("delete");
					action = "delete"; 
					}
				});	
		}
            });
	}	
}

function pedirJSON(toList){
/* aqui estamos intentando hacer una peticion al servidor campus-cloud-server.rb para que nos de el JSON*/
            $.ajax({
                url: "/teachers/"+toList,
		type:"GET",
		dataType: 'json',
                success: mostrarJSON,
                error: function(response){
			var html2='<div id="createDialog" title="Sorry">'+response.responseText+'</div>';
			$('#container').append(html2);
			$('#createDialog').dialog({
   				close: pedirJSON(action)
				});	
		}
            });
}

function logout(){
	$.ajax({
                url: "/logout",
		type:"POST",
                success: showindex,
                error: function(){
			alert("error");
		}
            });	
}

function showindex(){
	window.location.href="/";
}

/* Aqui estamos diciendo mediante las funciones que nos permite la libreria jQuery ($) que al elemento con id login_btn cuando le hagamos click ejecute la funcion pedirJSON*/
$(document).ready(function(){
    $("#li_profile").click(function () {
	
    });     
    $("#li_labs").click(function () {
      
    });
    $("#li_labs_list").click(function () {
        pedirJSON("list");
	action = "list";
    });
    $("#li_labs_create").click(function () {
        pedirJSON("create");
	action = "create";
    });
    $("#li_labs_delete").click(function () {
        pedirJSON("delete");
	action = "delete";
    });

    $("#logout").click(function () {
        logout();
    });
});
